package com.yami.shop.seckill.common.listener;

import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.ShopChangeStatusEvent;
import com.yami.shop.bean.order.GeneralActivitiesOrder;
import com.yami.shop.seckill.common.model.Seckill;
import com.yami.shop.seckill.common.service.SeckillService;
import com.yami.shop.seckill.common.service.SeckillSkuService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Author lth
 * @Date 2021/11/23 15:21
 */
@Component("seckillShopChangeStatusListener")
@AllArgsConstructor
public class ShopChangeStatusListener {

    private final SeckillService seckillService;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;


    @EventListener(ShopChangeStatusEvent.class)
    @Order(GeneralActivitiesOrder.SECKILL)
    public void seckillShopChangeStatusListener(ShopChangeStatusEvent event) {
        Long shopId = event.getShopId();
        ShopStatus shopStatus = event.getShopStatus();
        if (Objects.equals(shopStatus.value(), ShopStatus.OFFLINE.value())) {
            // 店铺下线，把该店铺的秒杀活动失效
            List<Seckill> invalidSeckillList = seckillService.invalidByShopId(shopId);
            // 清除缓存
            for (Seckill seckill : invalidSeckillList) {
                productService.removeProdCacheByProdId(seckill.getProdId());
                seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
                seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
            }
        }
    }
}
